<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #box{width: 100px;height:100px;background: red;position: absolute;left:0px;top:0px;}
    </style>
</head>
<body>
    <div id="box"></div>
</body>
<script>

    var box = document.querySelector("#box");

    var clientW = document.documentElement.clientWidth;
    var clientH = document.documentElement.clientHeight;
    var boxW = box.offsetWidth;
    var boxH = box.offsetHeight;

    // 按下
    box.addEventListener("mousedown", function(eve){
        var downE = eve || window.event;
        // 移动
        document.addEventListener("mousemove", move);
        function move(eve){
            var moveE = eve || window.event;

            // 计算元素的left和top值：鼠标相对于页面的坐标 - 鼠标相对于当前元素的坐标
            var l = moveE.pageX - downE.offsetX;
            var t = moveE.pageY - downE.offsetY;
            // 边界限定：如果小于最小值，设置为最小值，如果大于最大值，设置为最大值
            if(l<0) l=0;
            if(t<0) t=0;
            if(l > clientW - boxW){
                l = clientW - boxW
            }
            if(t > clientH - boxH){
                t = clientH - boxH
            }
            // 将处理好的位置信息，设置给元素
            box.style.left = l + "px";
            box.style.top = t + "px";
        }
        // 抬起
        document.addEventListener("mouseup", up);
        function up(){
            // 删除移动和抬起事件
            document.removeEventListener("mousemove", move);
            document.removeEventListener("mouseup", up);
        }
    })


    
</script>
</html>